import org.junit.Test;

public class leetCodeResult_0926 {
    @Test
    public void test() {
        //造一个ListNode链表数据依次是[4,1,8,4,5]
        ListNode node1 = new ListNode(4);
        ListNode node2 = new ListNode(1);
        ListNode node3 = new ListNode(8);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        //造一个ListNode链表数据依次是[5,6,1,8,4,5]
        ListNode node6 = new ListNode(5);
        ListNode node7 = new ListNode(6);
        ListNode node8 = new ListNode(1);

        node6.next = node7;
        node7.next = node8;
        node8.next = node3;
        System.out.println(getIntersectionNode(node6, node1).val);
    }
    /**
     * 160. 相交链表
     */

    public static class ListNode {
      int val;
      ListNode next;
      ListNode(int x) {
          val = x;
          next = null;
      }
    }

    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode result;
        while (headB != null) {
            result = headB;
            if (aroundListA(headA, headB)) {
                return result;
            }
            headB = headB.next;
        }
        return null;
    }

    public boolean isOneList(ListNode headA, ListNode headB) {
        while (headA != null && headB == headA) {
            headB = headB.next;
            headA = headA.next;
        }
        return headB == null && headA == null;
    }

    public boolean aroundListA(ListNode headA, ListNode headB) {
        while (!isOneList(headA, headB)) {
            headA = headA.next;
            if (headA == null) {
                return false;
            }
        }
        return true;
    }
}
